# 主界面（完整修复版）
import tkinter as tk
from tkinter import ttk, messagebox
from PIL import ImageTk, Image
from typing import Optional
import datetime
from gui.popup_window import MemoPopup
from db.database_manager import MySQLDatabaseManager

class MainWindow:
    def __init__(self, root: tk.Tk):
        self.root = root
        self.current_date = datetime.date.today()
        self.db = MySQLDatabaseManager()  # 添加数据库管理器
        self._bg_cache = None
        self._setup_ui()
        self._load_background()
        self._update_calendar()
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

    def _setup_ui(self) -> None:
        """初始化界面组件"""
        # 主框架（置于背景之上）
        self.main_frame = ttk.Frame(self.root, padding=10, style='TFrame')
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # 导航栏
        nav_frame = ttk.Frame(self.main_frame)
        ttk.Button(nav_frame, text="上个月", command=self.prev_month).pack(side=tk.LEFT)
        ttk.Button(nav_frame, text="下个月", command=self.next_month).pack(side=tk.LEFT)
        ttk.Label(nav_frame, textvariable=self.month_var,
                 font=('Arial', 12)).pack(side=tk.LEFT, padx=10)
        nav_frame.pack(pady=5)

        # 日历表格
        self.calendar_grid = ttk.Treeview(
            self.main_frame,
            columns=('Mon','Tue','Wed','Thu','Fri','Sat','Sun'),
            show='headings',
            height=6
        )

        # 设置列标题
        weekdays = ['周一','周二','周三','周四','周五','周六','周日']
        for col, day in enumerate(weekdays):
            self.calendar_grid.heading(col, text=day)
            self.calendar_grid.column(col, width=80, anchor=tk.CENTER)

        self.calendar_grid.pack(pady=10)
        self.calendar_grid.bind('<Double-1>', self._show_memo_popup)

    def _update_calendar(self) -> None:
        """更新日历显示（修复版）"""
        # 清空现有内容
        for item in self.calendar_grid.get_children():
            self.calendar_grid.delete(item)

        # 计算月份信息
        first_day = self.current_date.replace(day=1)
        last_day = (first_day + datetime.timedelta(days=32)).replace(day=1) - datetime.timedelta(days=1)
        weekday_offset = first_day.weekday()  # 周一=0, 周日=6

        # 填充日历
        day_num = 1
        for _ in range(6):  # 最多6行
            if day_num > last_day.day:
                break

            row = [''] * 7
            for col in range(7):
                if (day_num == 1 and col < weekday_offset) or day_num > last_day.day:
                    continue
                row[col] = str(day_num)
                day_num += 1

            self.calendar_grid.insert('', 'end', values=row)

    def _show_memo_popup(self, event):
        """显示备忘录弹窗"""
        item = self.calendar_grid.identify_row(event.y)
        if item:
            day = int(self.calendar_grid.item(item)['values'][0])
            date = self.current_date.replace(day=day)
            memos = self.db.get_memos(date)
            MemoPopup(self.root, date, self.db, memos)
            self._update_calendar()  # 刷新显示

    # 其他方法保持不变...
